//
//  CallManager.m
//  jmGouTong
//
//  Created by 王大虎 on 2022/9/22.
//  Copyright © 2022 seclery. All rights reserved.
//

#import "CallManager.h"
@import CallKit;
#import <JitsiMeetSDK/JitsiMeetSDK-Swift.h>

@interface CallManager ()


@end

@implementation CallManager


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.calls = [[NSMutableArray alloc]init];
    }
    return self;
}

-(Call *)callWithUUID:(NSUUID *)uuid{
    Call * ret_call = nil;
    for (Call * call in _calls) {
        if ([call.uuid isEqual:uuid]) {
            ret_call = call;
        }
    }
    return ret_call;
}


-(void)add:(Call *)call{
    [self.calls addObject:call];
    __weak typeof(self) weakSelf= self;
    call.stateChanged = ^{
        [weakSelf callsChangedHandler];
    };
    [self callsChangedHandler];
}

-(void)startCallWithHandle:(NSString *)handle VideoEnabled:(BOOL)videoEnabled{
    [self removeAllCalls];
    
    CXHandle *handle2 = [[CXHandle alloc]initWithType:CXHandleTypeGeneric value:@"Emroj Hossain"];
    
    NSUUID *uuid = [NSUUID UUID];
    
    CXStartCallAction *startCallAction = [[CXStartCallAction alloc]initWithCallUUID:uuid handle:handle2];
    [startCallAction setVideo:videoEnabled];
    
    Call *call = [[Call alloc]initWithUUID:uuid isOutgoing:YES handle:@"Emroj Hossain" isAudioCall:!videoEnabled];
    [self add:call];
    
    CXTransaction *transaction = [[CXTransaction alloc] initWithAction:startCallAction];
    
    [self requestTransaction:transaction];
    
    
}

-(void)end:(Call *)call{
    CXEndCallAction *endCallAction = [[CXEndCallAction alloc] initWithCallUUID:call.uuid];
    
    CXTransaction *transaction = [[CXTransaction alloc] initWithAction:endCallAction];
    
    [self requestTransaction:transaction];
}


-(void)setHeld:(Call *)call onHold:(BOOL)onHold{
    CXSetHeldCallAction *setHeldCallAction = [[CXSetHeldCallAction alloc]initWithCallUUID:call.uuid onHold:onHold];
    
    CXTransaction *transaction = [[CXTransaction alloc]init];
    [transaction addAction:setHeldCallAction];
    [self requestTransaction:transaction];
}


-(void)requestTransaction:(CXTransaction *)transaction{
    [JMCallKitProxy request:transaction completion:^(NSError * error) {
        if (error) {
            NSLog(@"Error requesting transaction: %@", error);
        }else{
            NSLog(@"Requested transaction successfully");
        }
    }];

}

-(void)remove:(Call *)call{
    [_calls removeObject:call];
    [self callsChangedHandler];
}

-(void)removeAllCalls{
    [self.calls removeAllObjects];
    [self callsChangedHandler];
}


@end
